package com.sotb.receiver;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.SmsMessage;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
/**
 * 
 * @author zsr lgb
 *
 */
public class MainMapActivity extends MapActivity {
	
	private final String SMS_ACTION = "android.provider.Telephony.SMS_RECEIVED";
	private static final int num = 3;
	private String regexp = "^-?([1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*|0?\\.0+|0)$";	//浮点数正则表达式,用于筛选短信
	private HistoryDbUtil historyDbUtil;
	private DatabaseHelper dbHelper;
	private SQLiteDatabase db;	
	private MapView mapView;
	private List<Overlay> mapOverlays;
	private Drawable markerImg;
    private FirstOverlay firstOverlay;
    private GeoPoint geoPoint;
    private MapController mapController;
    
    private int count = 0;		//用于双击地图事件的计数
    private long firstClick = 0;
    private long secondClick = 0;
    
    Handler smsHandler = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
        mapView = (MapView)findViewById(R.id.map);
        mapView.setBuiltInZoomControls(true);	//设置用于缩放地图的工具条
        mapView.setSatellite(true); 	//设置为卫星地图（没有偏置）
        mapController = mapView.getController();
        mapOverlays = mapView.getOverlays();

        markerImg = getResources().getDrawable(R.drawable.red_dot);
        //获取线程的looper对象作为参数
        smsHandler = new SMSHandler(getMainLooper());
        firstOverlay = new FirstOverlay(markerImg, this);
        
        //创建一个smsChecker监听短信
        smsChecker checker = new smsChecker();
        IntentFilter filter = new IntentFilter();
        filter.addAction(SMS_ACTION);
        this.registerReceiver(checker, filter);    
        
        
    }
	
	@Override
	protected void onResume() {
		super.onResume();
		firstOverlay.removeAllOverlayItem();	//清空标记
        Thread thread = new Thread(new ResumeGetInfo());
        thread.start();
	}
	
	/** 重新标记未完成项*/
	class ResumeGetInfo implements Runnable{
		List<String[]> notCompleteList;
		public void run() {
			dbHelper = new DatabaseHelper(MainMapActivity.this,"receiver_db", Constant.DB_VERSION);
			db = dbHelper.getWritableDatabase();
			historyDbUtil = new HistoryDbUtil(db);
			notCompleteList = historyDbUtil.ReceiveNotCompleteInFo();
			for(int i = 0; i < notCompleteList.size(); i++){
				markMap(notCompleteList.get(i));
			}
			db.close();
		}
		
	}
	
	/**在地图上标记求助点*/
	private void markMap(String[] s){
		if(isExist(s[2]))removeMark(s[2]);		//如果地图上已存在该号码的报警信息，则移除旧信息
		
		Double[] d = {Double.parseDouble(s[0]), Double.parseDouble(s[1])};
		
		geoPoint = new GeoPoint((int)(d[1]*Math.pow(10, 6)), (int)(d[0]*Math.pow(10, 6)));
		mapController.animateTo(geoPoint);
		mapController.setZoom(16);
		
		OverlayItem overlayitem = new OverlayItem(geoPoint, s[2], "");
        firstOverlay.addOverlayItem(overlayitem);		//添加item到图层
        mapOverlays.add(firstOverlay);		//添加图层到地图
	}
	
	/**移除标记点*/
	private void removeMark(String phoneNum){
		firstOverlay.removeOverlayItem(phoneNum);
	}
	
	
	/**响应双击地图事件*/
	@Override  
    public boolean dispatchTouchEvent(MotionEvent ev) {  
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {  
            count++;  
            if(count==1){  
                firstClick = System.currentTimeMillis();  
            }else if(count==2){  
                secondClick = System.currentTimeMillis();  
                if (secondClick - firstClick < 500) {  
                    mapView.getController().zoomInFixing((int) ev.getX(),  
                            (int) ev.getY());  
                }  
                count = 0;  
                firstClick = 0;  
                secondClick = 0;  
            }  
        }  
        return super.dispatchTouchEvent(ev);  
    }  

	/**检查地图上是否存在号码s的标记*/
	private boolean isExist(String s){
		for(int i = 0; i < firstOverlay.size(); i++){
			if(firstOverlay.getItem(i).getTitle().equals(s))return true;
		}
		return false;
	}
	
	/**在子线程中更新数据库*/
	class AddNewToDB implements Runnable{
		private String[] s;
		
		AddNewToDB(String[] s){
			this.s = s;
		}
		
		public void run() {
	        dbHelper = new DatabaseHelper(MainMapActivity.this,"receiver_db", Constant.DB_VERSION);//实例化数据库管理工具
			db = dbHelper.getWritableDatabase();
	        historyDbUtil = new HistoryDbUtil(db);
			historyDbUtil.insertData(s[2], s[0] + "," + s[1]);
			db.close();
		}
		
	}
	
	class WriteCompleteToDB implements Runnable{
		private String s;
		
		WriteCompleteToDB(String s){
			this.s = s;
		}
		
		public void run() {
	        dbHelper = new DatabaseHelper(MainMapActivity.this,"receiver_db", Constant.DB_VERSION);//实例化数据库管理工具
			db = dbHelper.getWritableDatabase();
	        historyDbUtil = new HistoryDbUtil(db);
			historyDbUtil.updateReceiveComplete(s);
			db.close();
		}			
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	/**接收短信的receiver*/
	class smsChecker extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			if (intent.getAction().equals(SMS_ACTION)){
				StringBuilder SMSContent = new StringBuilder();
				Bundle bundle = intent.getExtras();
				if (bundle != null){
					Object [] pdusObjects = (Object[]) bundle.get("pdus");
					SmsMessage [] msgs = new SmsMessage[pdusObjects.length];
					for(int i=0; i<pdusObjects.length; i++){
						msgs[i] = SmsMessage.createFromPdu((byte[]) pdusObjects[i]);
					}
					for(SmsMessage msg : msgs){
						SMSContent.append(msg.getDisplayMessageBody());
						SMSContent.append(","+msg.getDisplayOriginatingAddress());
					}					
					String [] latlngStr = SMSContent.toString().split(",");
					if (latlngStr.length == num && latlngStr[0].matches(regexp) && latlngStr[1].matches(regexp) /*&& latlngStr[2].matches(mobile_num)*/){					
						Message msg = smsHandler.obtainMessage();
						msg.obj = latlngStr;
						msg.what = Constant.ADD_MARK;
						msg.sendToTarget();
					}else
						System.out.println("sms not match");
				}
			}
		}		
	}
	
	/**处理短信的handler*/
	class SMSHandler extends Handler{
		
		public SMSHandler(Looper looper){
			super(looper);
		}
		@Override
		public void handleMessage(Message msg) {
			Thread thread;
			//处理得到的短信				
			switch(msg.what){
				case Constant.ADD_MARK:
					thread = new Thread(new AddNewToDB((String[])msg.obj));
					thread.start();
					markMap((String[])msg.obj);
					break;
				case Constant.COMPLETE:
					//接警完成
					thread = new Thread(new WriteCompleteToDB((String)msg.obj));
					thread.start();
					removeMark((String)msg.obj);
					break;
			}
			super.handleMessage(msg);
		}
		
	}

	/**创建menu*/
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, Constant.HISTORY_MENU_ITEM, 0, "历史记录");
		menu.add(0, Constant.EXIT, 1, "退出");
		return true;
	}

	/**响应menu点击事件*/
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case Constant.HISTORY_MENU_ITEM:{
			//跳转到history activity
			Intent intent = new Intent();
			intent.setClass(this, HistoryListActivity.class);
			startActivity(intent);
		}break;
		case Constant.EXIT:{
			finish();
		}
		}
		return true;
	}
	
	/**禁用返回键*/
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){
		}
		return false;
	}
	
}